import './Appear.scss';
import gsap from 'gsap';
import React, { RefObject, useRef } from 'react';
import { animateObj, animationBaseProps } from '../Animation';
import { createLabel } from '../utils/animationTools';

interface appearObj {
    name: string,
    ref: RefObject<HTMLDivElement>,
    key: string
}

export type appearRun = string;

const animationName = 'appear';

const Appear: React.FC<animationBaseProps<appearRun>> = (props) => {
  const appearObjList: appearObj[] = props.animateObj.run?.split('').map((item, index) => ({
    name: item,
    // eslint-disable-next-line react-hooks/rules-of-hooks
    ref: useRef<HTMLDivElement>(null),
    key: item + index
  })) || [];

  React.useEffect(() => {
    registerEffectAppear(props.animateObj.t1); // 初始化动画
    appearObjList.forEach((appearObj: appearObj, index) => {
      gsap.effects[animationName](appearObj.ref.current, {
        left: (index - (appearObjList.length - 1) / 2) * 160,
        animateObj: props.animateObj
      });
    });

    return function cleanup() {
      console.log('组件被卸载componentWillUnmount');
    };
  }, []);
  return <div className={'appear-box'}>

    {
      appearObjList.map((appear) => <div ref={appear.ref} key={appear.key} className={'appear-each-card'}>{appear.name}</div>)
    }
  </div>;
};

function registerEffectAppear(t1: GSAPTimeline) {
  gsap.registerEffect({
    name: animationName,
    effect: (targets: HTMLElement, config: {left: number, animateObj: animateObj<appearRun>}) => {
      t1.fromTo(targets, {
        y: -10,
        rotate: -180,
        left: 0,
        zoom: 0,
        opacity: 0
      }, {
        delay: config.animateObj.delay,
        duration: config.animateObj.duration,
        y: 0,
        rotate: 0,
        left: config.left,
        zoom: 1,
        opacity: 1,
        ease: 'back.inOut(3)'
      }, config.animateObj.position);
      createLabel(t1, config.animateObj);
      // 回调
      config.animateObj.callAnimate && config.animateObj.callAnimate(targets, t1);
    }
  });
}
// now we can use it like this:

export default Appear;
